package com.cloud.common.context;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class RequestContext {

    private static final ThreadLocal<HttpServletRequest> requestHolder = new ThreadLocal();
    private static final ThreadLocal<Boolean> maskHolder = new ThreadLocal<>();

    public static void maskData(boolean enable) {
        maskHolder.set(enable);
    }

    public static boolean isMaskData() {
        Boolean enable = maskHolder.get();
        return enable == null ? true : enable;
    }

    public static void remove() {
        requestHolder.remove();
    }

    public static void set(HttpServletRequest request) {
        requestHolder.set(request);
    }

    public static HttpServletRequest getRequest() {
        return requestHolder.get();
    }

    public static String getRequestIP() {
        HttpServletRequest request = getRequest();
        if (request != null) {
            String ip = request.getHeader("X-Forwarded-For");
            if (StringUtils.isEmpty(ip)) {
                ip = request.getHeader("X-Real-IP");
            }
            if (StringUtils.isEmpty(ip)) {
                ip = request.getRemoteAddr();
            } else {
                ip = ip.split(",")[0];
            }
            return ip.trim();
        }
        return "";
    }

    public static String getCookie(String name) {
        HttpServletRequest request = getRequest();
        if (request != null) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(name)) {
                        return cookie.getValue();
                    }
                }
            }
        }
        return "";
    }

    public static String getReferer() {
        HttpServletRequest request = getRequest();
        if (request != null) {
            return request.getHeader(HttpHeaders.REFERER);
        }
        return "";
    }

    public static String getUserAgent() {
        HttpServletRequest request = getRequest();
        if (request != null) {
            return request.getHeader(HttpHeaders.USER_AGENT);
        }
        return "";
    }

    public static String getHeader(String name) {
        HttpServletRequest request = getRequest();
        if (request != null) {
            return request.getHeader(name);
        }
        return "";
    }

}
